import random
import tkinter as tk
from tkinter import font, messagebox
from typing import List
from PIL import Image, ImageTk


class LotteryApp:
    def __init__(self, root: tk.Tk) -> None:
        self.root = root
        self.root.title("抽奖小程序")
        self.root.geometry("700x750")

        # 初始化图片
        try:
            self.image = self._load_image("logo.png", (100, 100))
        except Exception as e:
            messagebox.showerror("错误", f"无法加载图片: {str(e)}")
            self.image = None

        # 初始化人员名单
        try:
            self.all_participants = self._load_participants('name.txt')
        except Exception as e:
            messagebox.showerror("错误", f"无法加载人员名单: {str(e)}")
            self.all_participants = []

        self.current_participants = self.all_participants.copy()
        self.winners: List[str] = []
        self.is_drawing = False

        # 初始化界面变量
        self.status_message = tk.StringVar()
        self.current_winner = tk.StringVar()
        self.num_winners = tk.StringVar(value="1")

        self._create_ui()
        self._update_status()

    def _load_image(self, path: str, size: tuple[int, int]) -> ImageTk.PhotoImage:
        """加载并调整图片大小"""
        image = Image.open(path)
        image = image.resize(size)
        return ImageTk.PhotoImage(image)

    def _load_participants(self, path: str) -> List[str]:
        """从文件加载参与者名单"""
        with open(path, 'r', encoding='utf-8') as file:
            return [line.strip() for line in file if line.strip()]

    def _create_ui(self) -> None:
        """创建用户界面"""
        # 图片显示
        if self.image:
            tk.Label(self.root, image=self.image).place(x=5, y=5)

        # 状态显示
        status_frame = tk.Frame(self.root)
        status_frame.pack()
        tk.Label(status_frame, textvariable=self.status_message,
                 font=("SimSun", 22, "bold")).pack()

        # 控制按钮
        control_frame = tk.Frame(self.root)
        control_frame.pack(pady=5)

        button_font = font.Font(family="SimSun", size=24, weight="bold")
        tk.Button(control_frame, text="新一轮", command=self.reset_lottery,
                  width=10, height=1, font=button_font).pack(side=tk.LEFT, padx=5)

        tk.Label(control_frame, text="中奖人数：",
                 font=("SimSun", 24, "bold")).pack(side=tk.LEFT, padx=20)
        tk.Entry(control_frame, textvariable=self.num_winners, width=5,
                 validate='key', font=("SimSun", 24, "bold"),
                 validatecommand=(self.root.register(self._validate_input), '%P')).pack(side=tk.LEFT)

        # 抽奖按钮
        self.lottery_button = tk.Button(self.root, text="开始", command=self.toggle_lottery,
                                        width=45, height=1, font=button_font)
        self.lottery_button.pack(pady=5)

        # 结果显示
        result_frame = tk.Frame(self.root)
        result_frame.pack()
        tk.Label(result_frame, text="抽奖结果", font=("SimSun", 24, "bold"),
                 fg="#f13a09").pack(side=tk.TOP)
        tk.Label(result_frame, textvariable=self.current_winner,
                 font=("SimSun", 24, "bold"), fg='#f13a09', wraplength=150).pack(pady=30)

    def toggle_lottery(self) -> None:
        """切换抽奖状态"""
        if not self.is_drawing:
            """验证抽奖人数是否有效"""
            num_winners = int(self.num_winners.get())
            if len(self.current_participants) < num_winners:
                self.current_winner.set("人员数量不足")
                self.is_drawing = False
                self.lottery_button.config(text="开始")
                return

            self.is_drawing = True
            self._start_lottery()
            # 修改按钮文字为"停止"
            self.lottery_button.config(text="停止")
        else:
            # 先停止抽奖并显示结果
            self._stop_lottery()
            # 再设置is_drawing为False
            self.is_drawing = False
            # 修改按钮文字为"开始"
            self.lottery_button.config(text="开始")

    def _start_lottery(self) -> None:
        self._update_lottery()

    def _stop_lottery(self) -> None:
        """停止抽奖并显示结果"""
        try:
            num_winners = int(self.num_winners.get())
            winners = random.sample(self.current_participants, num_winners)
            self.current_participants = [p for p in self.current_participants if p not in winners]
            self.winners.extend(winners)
            # 显示最终结果
            self.current_winner.set('  '.join(winners))
            self.root.update()
            self._update_status()
        except Exception as e:
            messagebox.showerror("错误", f"抽奖失败: {str(e)}")

    def _update_lottery(self) -> None:
        """更新抽奖显示"""
        if self.is_drawing:
            try:
                # 随机打乱当前参与者顺序
                num_winners = int(self.num_winners.get())
                display_names = random.sample(self.current_participants, num_winners)
                # 将列表转换为字符串显示
                self.current_winner.set('  '.join(display_names))
                # 设置滚动速度（100ms更新一次）
                self.root.after(100, self._update_lottery)
            except Exception as e:
                messagebox.showerror("错误", f"抽奖过程出错: {str(e)}")
                self.is_drawing = False
                self.lottery_button.config(text="开始")

    def _validate_input(self, new_text: str) -> bool:
        """验证输入是否为数字"""
        return new_text.isdigit() or new_text == ""

    def reset_lottery(self) -> None:
        """重置抽奖"""
        if not self.is_drawing:
            self.current_participants = self.all_participants.copy()
            self.winners = []
            self._update_status()
            self.current_winner.set("")

    def _update_status(self) -> None:
        """更新状态显示"""
        total = len(self.all_participants)
        won = len(self.winners)
        remaining = total - won
        self.status_message.set(f"总数：{total}|已中：{won}|未中：{remaining}")


if __name__ == "__main__":
    root = tk.Tk()
    app = LotteryApp(root)
    root.mainloop()
